package com.example.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response  = (HttpServletResponse) servletResponse;
        final String url = request.getRequestURL().toString();
         log.info("url:{}",url);
         //判断是否包含login
        if(url.contains("login"))
        {
            log.info("登录操作放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3.获取请求头的令牌
        String jwt = request.getHeader("token");
       //4.判断是否存在，如果不存在，返回错误结果
        if(!StringUtils.hasLength("jwt"))
        {
            log.info("请求头token为空，返回未登录信息");
             Result error = Result.error("NOT_LOGIN");
            //手动转换  对象 json
            String notlogin = JSONObject.toJSONString(error);
            response.getWriter().write(notlogin);
            return;
        }
        //5.校验jwt
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e)
        {
         e.printStackTrace();
         log.info("解析令牌失败，返回错误信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换  对象 json
            String notlogin = JSONObject.toJSONString(error);
            response.getWriter().write(notlogin);
            return;
        }

    //6.放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
